from selenium import webdriver  
from selenium.webdriver.common.by import By  
from selenium.webdriver.support.ui import WebDriverWait  
from selenium.webdriver.support import expected_conditions as EC  
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys, json


def openMiguHtml(miguUrl):
    # 创建浏览器驱动对象  

    driver = webdriver.Safari() # 使用Chrome浏览器为例  
    driver.maximize_window()  # 浏览器全屏
    # 打开目标网页  
    # 西甲集锦：皇马vs马洛卡
    #ul = 'https://www.miguvideo.com/p/live/120000459675'
    # driver.get(miguUrl) 
    print('开始打开url')
    return driver


def scrollToElement(driver, element) :
    driver.execute_script("arguments[0].scrollIntoView();", element)


# 模拟点击元素
def clickElement(driver, element) :

    # scrollToElement(driver, element)
    time.sleep(1)

    # 获取鼠标指针的当前位置  
    mouse_position = driver.execute_script("return {x: window.screenX, y: window.screenY}")  
    
    # 构建鼠标点击的动作链  
    actions = ActionChains(driver)  
    actions.move_to_element(element)  # 将鼠标指针移动到div元素的位置  
    actions.click()  # 触发点击事件 
    # 执行动作链并等待点击事件完成  
    actions.perform() 


#保存json文件
def saveJsonData(gameJsonPath, jsonData) :
    
    with open(gameJsonPath, "w", encoding='utf-8') as file:  
        #file.write(json_data)
        json.dump(jsonData, file, ensure_ascii=False, indent=4)
        print('保存json数据完成')

def get_song_dic(driver,itemID) :

	#https://www.kuwo.cn/playlist_detail/3001661381
	playlistUrl = 'https://www.kuwo.cn/playlist_detail/'+itemID
	# driver = openMiguHtml(playlistUrl)
	driver.get(playlistUrl)

	# 移除广告弹窗
	ar = driver.find_elements(By.CSS_SELECTOR, ".model_out")
	if len(ar) > 0 :
		driver.execute_script("arguments[0].style.display = 'none';", ar[-1])
	time.sleep(2)
	print("广告弹窗移除完成")

	listDic = []
	isHavePage = True
	while isHavePage:
		
		# 找到当前页面所有的歌单列表（会包含其他元素，所以需要过滤下）
		divList = driver.find_elements(By.CSS_SELECTOR, ".song_item.flex_c")
		if len(divList) > 0 :
			for div in divList :
				titleDivs = div.find_elements(By.CSS_SELECTOR, "div.song_name.flex_c")
				artistDivs = div.find_elements(By.CSS_SELECTOR, "div.song_artist")
				if len(titleDivs) > 0 and len(artistDivs) > 0 :
					ti = titleDivs[-1].text.replace(' ','')
					ar = artistDivs[-1].text.replace(' ','')
					#得到歌曲名和歌手名
					songDic = {"title":ti, "artist":ar}
					listDic.append(songDic)

			#找到下一页元素，然后点击
			nextPages = driver.find_elements(By.CSS_SELECTOR, ".li-page.iconfont.icon-icon_pagedown")
			if len(nextPages) > 0 :
				print('得到下一页')

				if 'notPointer' in nextPages[0].get_attribute('class') :
					print('页面已全部加载完毕')
					break;

				scrollToElement(driver, nextPages[0])
				time.sleep(3)
				nextPages[0].click()
				print('点击了下一页, 等待3秒')
				time.sleep(3)
			else :
				#找不到下一页，则直接结束循环
				break;

	print(f'\n\n得到结果：{len(listDic)}\n')
	print(listDic)
	return listDic


driver = openMiguHtml('')

def readJson(path) :
	with open(path, "r", encoding='utf-8') as file:  
		jsonArr = json.load(file)
		return jsonArr
	return []

#读取歌单并循环
jsonArr = readJson('./data.json')
for playlistDic in jsonArr :
	itemid = playlistDic['itemID']
	if len(itemid) > 3 :
		songArr = get_song_dic(driver, itemid)
		if len(songArr) > 0 :
			playlistDic['playlists'] = songArr
			break

saveJsonData('./ret.json', jsonArr)
print('程序结束，3秒后退出')
time.sleep(3)


driver.find_elements(By.XPATH, "//a[contains(@text, '最热')]")



# 假设driver是你的WebDriver实例  
element = driver.find_elements(By.CSS_SELECTOR, 'a[data-v-17ae183a]')







